package cn.tianyigps.tianyigpsgatherchecker.service;

import cn.tianyigps.tianyigpsgatherchecker.constant.RuleTypeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import static cn.tianyigps.tianyigpsgatherchecker.constant.UrlConstant.CAR_ALLEQUIPMENT_URL;

@Service
public class FindCarAllEquIds {
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    RedisTemplate redisTemplate;
    public String findCarAllEquIds(String equipmentId ) {
        String rest = (String) redisTemplate.opsForValue().get( RuleTypeEnum.GATHER.getType() + equipmentId + "other");
        if (Optional.ofNullable(rest).isPresent()) {
            return rest;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("equipmentId", equipmentId);
        rest = restTemplate.getForObject(CAR_ALLEQUIPMENT_URL, String.class, params);
        if (!Optional.ofNullable(rest).isPresent()) {
            return null;
        }
        if(!StringUtils.isEmpty(rest)){
            redisTemplate.expire(equipmentId, 300, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set( RuleTypeEnum.GATHER.getType() + equipmentId + "other", rest);
            Random random = new Random();
            redisTemplate.expire( RuleTypeEnum.GATHER.getType() + equipmentId + "other", random.nextInt(60 * 60) + 120 * 60, TimeUnit.SECONDS);
        }
        return rest;
    }
}
